<?php

namespace app\controller\admin\genshinteam;

use app\model\api\GenshinRelics;
use app\model\api\GenshinWeapon;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use laytp\library\Tree;

/**
 * 菜单控制器
 */
class Weapon extends Backend
{

    public $model;
    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public function _initialize()
    {
        $this->model = new GenshinWeapon();
    }


    /**
     * 武器列表
     * @return false|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function weapon(){
        $data = $this->model->getAllWeapon();
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());

        $insData['name'] = $post['name'];
        $insData['icon']  = $post['icon'];
        $insData['img']  = $post['img'];
        $insData['weapon_id']  = $post['weapon_id'];
        $insData['rarity']  = $post['rarity'];
        $insData['type_name']  = $post['type_name'];
        try {
            $save = $this->model->save($insData);
            if (!$save) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row->name = $post['name'];
        $row->icon  = $post['icon'];
        $row->rarity  = $post['rarity'];
        $row->weapon_id  = $post['weapon_id'];
        $row->type_name  = $post['type_name'];
        try {
            $save = $row->save();
            if ($save === false) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function info(){
        $id = $this->request->param('id');
        $relics = $this->model->where('id',$id)->find()->toArray();
        $relics['name']   = !empty($relics['name'])?$relics['name']:'';
        $relics['icon']   = !empty($relics['icon'])?$relics['icon']:'';
        $relics['img']   = !empty($relics['img'])?$relics['img']:'';
        $relics['rarity']   = !empty($relics['rarity'])?$relics['rarity']:'';
        $relics['type_name']   = !empty($relics['type_name'])?$relics['type_name']:'';
        return $this->success('获取成功', $relics);
    }
}
